package org.lilystudio.smarty4j.statement.function;

import java.io.Writer;

import org.apache.commons.lang3.StringUtils;
import org.lilystudio.smarty4j.Context;
import org.lilystudio.smarty4j.Engine;
import org.lilystudio.smarty4j.Template;
import org.lilystudio.smarty4j.TemplateException;
import org.lilystudio.smarty4j.statement.LineFunction;
import org.lilystudio.smarty4j.statement.ParameterCharacter;

import com.flying.common.log.Logger;
import com.flying.common.util.Constants;
import com.flying.common.util.ServiceHelper;
import com.flying.framework.data.Data;
import com.flying.framework.module.LocalModule;
import com.flying.framework.util.SmartyUtils;

/**
 * @author wanghaifeng
 * 
 */
public class $form extends LineFunction {
	private final static Logger logger = Logger.getLogger($jqueryui_grid.class);

	private static ParameterCharacter[] definitions = {
			new ParameterCharacter(ParameterCharacter.STROBJECT, null, "id"),
			new ParameterCharacter(ParameterCharacter.STROBJECT, null, "action"),
			new ParameterCharacter(ParameterCharacter.STROBJECT, null, "template"),
			new ParameterCharacter(ParameterCharacter.STROBJECT, null, "moduleId"),
			new ParameterCharacter(ParameterCharacter.STROBJECT, null, "view"),
			new ParameterCharacter(ParameterCharacter.STROBJECT, null, "params")
		};

	
	public void execute(Context context, Writer writer, Object[] args)
			throws Exception {
		//
		LocalModule module = (LocalModule) context.get(Constants.MODULE_UID);
		
		String id 		= (String) args[0];
		String action 	= (String) args[1];
		final String template = args[2]!=null?(String) args[2] : module.getModuleConfig().getConfig("template.form");
		final String moduleId 	= args[3] == null?module.getId(): (String) args[3];
		String form 	= (String) args[4];
		String params 	= (String) args[5];
		
		Data formData = ServiceHelper.invoke("pas", "FormService:findByModuleAndCode", new Data("module", moduleId,"code", form));
		context.set("_form", formData);
		Long formId = formData.getLong("formId");
		
		context.set("_fields", ServiceHelper.invoke("pas", "FieldService:findByFormId", new Data("form_id", formId)).get("rows"));
		context.set("_actions", ServiceHelper.invoke("pas", "ActionService:findByFormId", new Data("form_id", formId)).get("rows"));
		
		if(params != null) {
			String[] tmps = StringUtils.split(params, ";");
			for(String tmp: tmps) {
				if(tmp != null) {
					String[] kv = StringUtils.split(tmp, "=");
					if(kv.length == 2)
						context.set(kv[0].trim(), kv[1].trim());
				}
			}
		}
		
		Engine engine = SmartyUtils.getEngine(module);
		context.set("id", id);
		context.set("action", action);
		
		Template t;
		try {
			t = engine.getTemplate(template);
			t.merge(context, writer);
		} catch (TemplateException e) {
			logger.error(e);
		}
		
	}
	
	public ParameterCharacter[] getDefinitions() {
		return definitions;
	}
}
